package com.uduemc.biso.node.module.service.impl;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.uduemc.biso.node.core.common.entities.publishdata.databody.pagebannerdata.BannerItem;
import com.uduemc.biso.node.core.entities.HRepertory;
import com.uduemc.biso.node.core.entities.SBannerItem;
import com.uduemc.biso.node.core.entities.SRepertoryQuote;
import com.uduemc.biso.node.core.entities.custom.BannerItemQuote;
import com.uduemc.biso.node.module.mapper.SBannerItemMapper;
import com.uduemc.biso.node.module.service.HRepertoryService;
import com.uduemc.biso.node.module.service.SBannerItemService;
import com.uduemc.biso.node.module.service.SRepertoryQuoteService;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

@Service
public class SBannerItemServiceImpl implements SBannerItemService {

	@Autowired
	private SBannerItemMapper sBannerItemMapper;

	@Autowired
	private HRepertoryService hRepertoryServiceImpl;

	@Autowired
	private SRepertoryQuoteService sRepertoryQuoteServiceImpl;

	@Override
	public SBannerItem insertAndUpdateCreateAt(SBannerItem sBannerItem) {
		sBannerItemMapper.insert(sBannerItem);
		SBannerItem findOne = findOne(sBannerItem.getId());
		Date createAt = sBannerItem.getCreateAt();
		if (createAt != null) {
			sBannerItemMapper.updateCreateAt(findOne.getId(), createAt, SBannerItem.class);
		}
		return findOne;
	}

	@Override
	public SBannerItem insert(SBannerItem sBannerItem) {
		sBannerItemMapper.insert(sBannerItem);
		return findOne(sBannerItem.getId());
	}

	@Override
	public SBannerItem insertSelective(SBannerItem sBannerItem) {
		sBannerItemMapper.insertSelective(sBannerItem);
		return findOne(sBannerItem.getId());
	}

	@Override
	public SBannerItem updateById(SBannerItem sBannerItem) {
		sBannerItemMapper.updateByPrimaryKey(sBannerItem);
		return findOne(sBannerItem.getId());
	}

	@Override
	public SBannerItem updateByIdSelective(SBannerItem sBannerItem) {
		sBannerItemMapper.updateByPrimaryKeySelective(sBannerItem);
		return findOne(sBannerItem.getId());
	}

	@Override
	public SBannerItem findOne(Long id) {
		return sBannerItemMapper.selectByPrimaryKey(id);
	}

	@Override
	public List<SBannerItem> findAll(Pageable pageable) {
		int pageNumber = pageable.getPageNumber();
		int pageSize = pageable.getPageSize();
		PageHelper.startPage(pageNumber, pageSize);
		return sBannerItemMapper.selectAll();
	}

	@Override
	public void deleteById(Long id) {
		sBannerItemMapper.deleteByPrimaryKey(id);
	}

	@Override
	public int deleteByHostSiteId(long hostId, long siteId) {
		Example example = new Example(SBannerItem.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("hostId", hostId);
		criteria.andEqualTo("siteId", siteId);
		return sBannerItemMapper.deleteByExample(example);
	}

	@Override
	public int deleteByHostSiteBannerId(long hostId, long siteId, long bannerId) {
		Example example = new Example(SBannerItem.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("hostId", hostId);
		criteria.andEqualTo("siteId", siteId);
		criteria.andEqualTo("bannerId", bannerId);
		return sBannerItemMapper.deleteByExample(example);
	}

	@Override
	public List<SBannerItem> findByHostSiteBannerId(long hostId, long siteId, long bannerId) {
		Example example = new Example(SBannerItem.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("hostId", hostId);
		criteria.andEqualTo("siteId", siteId);
		criteria.andEqualTo("bannerId", bannerId);
		List<SBannerItem> listSBannerItem = sBannerItemMapper.selectByExample(example);
		example.setOrderByClause("`s_banner_item`.`order_num` ASC, `s_banner_item`.`id` ASC");
		if (CollectionUtils.isEmpty(listSBannerItem)) {
			return null;
		}
		return listSBannerItem;
	}

	@Transactional
	@Override
	public void save(long hostId, long siteId, long bannerId, List<BannerItem> bannerItems, List<BannerItemQuote> listBannerItemQuote) {

		// 首先找出现有的所有的 bannerItem 数据
//		List<SBannerItem> listSBannerItem = findByHostSiteBannerId(hostId, siteId, bannerId);
		if (CollectionUtils.isEmpty(bannerItems)) {
			// 没有banner item 数据的情况
			if (!CollectionUtils.isEmpty(listBannerItemQuote)) {
				listBannerItemQuote.forEach(element -> {
					SBannerItem sbannerItem = element.getSbannerItem();
					deleteById(sbannerItem.getId());
					sRepertoryQuoteServiceImpl.deleteByHostSiteAimIdAndType(hostId, siteId, (short) 9, sbannerItem.getId());
				});
			}
		} else {
			Iterator<BannerItem> iterator = bannerItems.iterator();
			int i = 0;
			while (iterator.hasNext()) {
				BannerItem pageBannerItem = iterator.next();
				// 首先验证是否存在资源数据，如果不存在资源数据则抛出异常
				HRepertory hRepertory = hRepertoryServiceImpl.findByHostIdAndId(pageBannerItem.getRepertoryId(), hostId);
				if (hRepertory == null) {
					throw new RuntimeException(
							"验证参数 repertoryId 是否存在时出现异常 pageBannerItem.getRepertoryId()： " + pageBannerItem.getRepertoryId() + " | " + hostId);
				}
				// 是否存在，存在则更新，不存在则插入
				SBannerItem sBannerItem;
				SBannerItem save;
				if (CollectionUtils.isEmpty(listBannerItemQuote) || i >= listBannerItemQuote.size()) {
					// 原来数据没有或者未
					sBannerItem = new SBannerItem();
					// 插入
					sBannerItem.setHostId(hostId).setSiteId(siteId).setBannerId(bannerId).setOrderNum(pageBannerItem.getOrderNum())
							.setConfig(pageBannerItem.getItemConfig());
					save = insert(sBannerItem);
				} else {
					sBannerItem = listBannerItemQuote.get(i).getSbannerItem();
					// 修改
					sBannerItem.setOrderNum(pageBannerItem.getOrderNum()).setConfig(pageBannerItem.getItemConfig());
					save = updateById(sBannerItem);
				}

				if (save == null || save.getId() == null || save.getId().longValue() < 1) {
					throw new RuntimeException("保存 s_banner_item 数据出现异常 sBannerItem： " + sBannerItem.toString());
				}

				// 对其资源引用数据进行操作
				List<SRepertoryQuote> listSRepertoryQuote = sRepertoryQuoteServiceImpl.findByHostSiteAimIdAndType(hostId, siteId, (short) 9, save.getId());
				if (CollectionUtils.isEmpty(listSRepertoryQuote)) {
					SRepertoryQuote insertSRepertoryQuote = insertSRepertoryQuoteBySBannerItem(save, pageBannerItem, hRepertory);
					if (insertSRepertoryQuote == null || insertSRepertoryQuote.getId() == null || insertSRepertoryQuote.getId().longValue() < 1) {
						throw new RuntimeException("写入 s_repertory_quote 数据出现异常 save： " + save.toString() + " pageBannerItem: " + pageBannerItem.toString());
					}
				} else {
					if (listSRepertoryQuote.size() > 1) {
						for (int j = 1; j < listSRepertoryQuote.size(); j++) {
							sRepertoryQuoteServiceImpl.deleteById(listSRepertoryQuote.get(j).getId());
						}
					}
					SRepertoryQuote sRepertoryQuote = listSRepertoryQuote.get(0);
					sRepertoryQuote.setRepertoryId(hRepertory.getId()).setConfig(pageBannerItem.getRepertoryConfig());
					SRepertoryQuote updateSRepertoryQuote = sRepertoryQuoteServiceImpl.updateById(sRepertoryQuote);
					if (updateSRepertoryQuote == null || updateSRepertoryQuote.getId() == null || updateSRepertoryQuote.getId().longValue() < 1) {
						throw new RuntimeException("更新 s_repertory_quote 数据出现异常 save： " + save.toString() + " pageBannerItem: " + pageBannerItem.toString());
					}
				}
				// 自增
				i++;
			}
			if (!CollectionUtils.isEmpty(listBannerItemQuote)) {
				// 删除多余部分
				while (i < listBannerItemQuote.size() && listBannerItemQuote.get(i) != null) {
					SBannerItem sBannerItem = listBannerItemQuote.get(i++).getSbannerItem();
					deleteById(sBannerItem.getId());
					sRepertoryQuoteServiceImpl.deleteByHostSiteAimIdAndType(hostId, siteId, (short) 9, sBannerItem.getId());
				}
			}
		}

	}

	protected SRepertoryQuote insertSRepertoryQuoteBySBannerItem(SBannerItem save, BannerItem bannerItem, HRepertory hRepertory) {
		SRepertoryQuote sRepertoryQuote = new SRepertoryQuote();
		sRepertoryQuote.setHostId(save.getHostId()).setSiteId(save.getSiteId()).setRepertoryId(hRepertory.getId()).setType((short) 9).setAimId(save.getId())
				.setOrderNum(save.getOrderNum()).setConfig(bannerItem.getRepertoryConfig());
		return sRepertoryQuoteServiceImpl.insert(sRepertoryQuote);
	}

	@Override
	public PageInfo<SBannerItem> findPageInfoAll(long hostId, long siteId, int pageNum, int pageSize) {
		Example example = new Example(SBannerItem.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("hostId", hostId);
		criteria.andEqualTo("siteId", siteId);
		PageHelper.startPage(pageNum, pageSize);
		List<SBannerItem> listSBannerItem = sBannerItemMapper.selectByExample(example);
		PageInfo<SBannerItem> result = new PageInfo<>(listSBannerItem);
		return result;
	}
}
